import React from 'react'
import {withRouter,} from 'react-router-dom'
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout"
import './pro-apply.css'
import './step.css'
import proTitleBlock from '../../res/images/web/pro_apply/装饰@2x.png'
import veritySrc from '../../res/images/web/pro_apply/认证@2x.png'
import CustomButton from "../../shared-components/CustomButton/CustomBotton";
import LocalStorageService from "../../utils/LocalStorageService";
import {getApplyPlanProFlagReq, getQuizListReq, getUserDetailReq, submitApplyPlanProReq,} from "../../apis/goApis";
import RealInfoForm from "../userInfo/componets/RealInfo/RealInfoForm";
import 审核中src from "../../res/images/web/pro_apply/ID card 审核中@2x.png"
import 审核拒绝src from "../../res/images/web/pro_apply/ID card 未通过@2x.png"
import 审核通过src from "../../res/images/web/pro_apply/ID card 已通过@2x.png"
import SelectDot from "./SelectDot/SelectDot";

// 1.apis/addscheme //添加方案
//
// req:

// }
//


//
// resp:
//     flag string //-1=没有审批记录,1=审批通过,0=未通过,3=审批中
//
// 4.apis/setspecialistinfo //设置专家信息
//
// req:表单
// type SetSpecialistInfoJson struct {
//     Uid      string
//     Iconurl  string //用户头像url，换头像传"avatar"
//     Nickname string //用户昵称
//     Gl       string //擅长类型
//     Gs       string //擅长赛事
//     Txt      string //专家自我介绍
// }
// apis/getspecialistdetail  //获取专家细节页面
// type GetSpecialistDetailJson struct {
//     Uid string `binding:"required"`
//     P   int
// }
class ProApply extends React.Component {

    constructor(props) {
        super(props)
        this.letters = 'ABCDEFGH'
        this.uid = LocalStorageService.get('userid')
        this.state = {
            status: 'init',
            isRealNameVerify: false,
            // isProVerify: false,
            proVerifyStatus: -1,
            stepsData: [
                {
                    title: '实名认证',
                    finished: false,
                    cur: false,
                },
                {
                    title: '答题测试',
                    finished: false,
                    cur: false,
                },
                {
                    title: '提交审核',
                    finished: false,
                    cur: false,
                },
            ],
            quizList: [],
        }

    }

    componentDidMount() {
        this.getVerify()
    }

    getVerify() {

        getApplyPlanProFlagReq({
            Uid: this.uid,
        }).then(resp => {
            return resp.data.Flag
        }).then((proVerifyStatus) => {
            this.setState({
                proVerifyStatus,
            }, () => {
                if (proVerifyStatus === -1) {
                    this.onInitStatus()
                } else {
                    this.onResultStatus()
                }
            })
        })
    }

    onInitStatus() {
        getUserDetailReq({
            uid: this.uid,
        }).then((resp) => {
            const d = resp.data.ok
            const isRealNameVerify = d.Realname.length > 0
            const stepsData = [...this.state.stepsData,]
            let status = 'init'
            if (isRealNameVerify) {
                stepsData[0].finished = true
                stepsData[0].finished = true
                stepsData[1].cur = true
                status = 'quiz'
                this.getQuiz()
            }
            this.setState({
                isRealNameVerify,
                status,
            })
        })
    }

    onResultStatus() {
        this.setState({
            status: 'apply',
        })
    }

    getQuiz() {
        getQuizListReq({
            Pid: -1,
        })
            .then((resp) => {
                const list = resp.data.ok
                if (list) {
                    list.forEach(quiz => {
                        quiz.Option = quiz.Option.map(q => ({text: q, select: false,}))
                    })
                    this.setState({
                        quizList: list,
                    })
                }
            })
    }

    startRealNameVerify() {
        const stepsData = [...this.state.stepsData,]
        stepsData[0].cur = true
        this.setState({
            status: 'realName',
            stepsData,
        })
    }

    onRealNameVerifySuccess() {
        const stepsData = [...this.state.stepsData,]
        stepsData[0].finished = true
        stepsData[0].cur = false
        stepsData[1].cur = true
        this.setState({
            status: 'quiz',
            stepsData,
        }, () => {
            this.getQuiz()
        })
    }

    onOptionClick(quizIndex, optionIndex) {
        const qi = quizIndex
        const oi = optionIndex
        const list = [...this.state.quizList,]
        const select = list[qi].Option[oi].select
        list[qi].Option[oi].select = !select
        this.setState({
            quizList: list,
        })
    }

    submitApply() {
        const list = this.state.quizList
        // 2.apis/applyspecialist //申请成为专家
        //
        // req:
        //     type ApplySpecialistJson struct {
        //     Uid    string
        //     Answer map[int][]string  //题目id和答案
        // }
        const answer = {}
        list.map((quiz) => {
            let key = quiz.Id
            let option = []
            // let select = quiz.Option.map((o, oIndex) => {
            //     if (o.select) {
            //         return oIndex
            //     }
            // })
            for (let i = 0; i < quiz.Option.length; i++) {
                let o = quiz.Option[i]
                if (o.select) {
                    option.push(this.letters[i])
                }
            }
            answer[key] = option
        })

        submitApplyPlanProReq({
            Uid: this.uid,
            Answer: answer,
        }).then(resp => {
            if (resp.data.ok) {
                this.getVerify()
            }
        })

    }

    reApply() {
        this.onInitStatus()
    }

    renderApplyResultTemplate(status) {
        if (status === -1) {
            return null
        }
        // -1=没有审批记录,1=审批通过,0=未通过,3=审批中


        let statusDatas = {
            // '0': ,
            '0': {
                src: 审核拒绝src,
                text: '您的专家申请未通过',
                color: '#FA7268',
                button: <CustomButton
                    onClick={() => this.reApply()}
                >重新申请</CustomButton>,
            },
            '1': {
                src: 审核通过src,
                text: '您的专家申请已通过',
                color: '#009904',
                button: <CustomButton
                    onClick={() => this.props.history.push('./set_pro_detail')}
                >设置信息</CustomButton>,
            },
            '3': {
                src: 审核中src,
                text: '您的专家申请审核中…',
                color: '#213A4B',
                button: <CustomButton
                    onClick={() => this.props.history.goBack()}
                >返回</CustomButton>,
            },
        }

        let imgSrc = statusDatas[status].src
        let imgStyle = {
            width: '109ox',
            height: '78px',
        }
        let text = statusDatas[status].text
        let textStyle = {
            fontSize: '16px',
            fontWeight: 500,
            color: statusDatas[status].color,
            lineHeight: '22px',
        }

        return <div className='text-align-center'>

            <div style={{marginTop: '116px',}}>
                <img src={imgSrc} alt="" style={imgStyle}/>
                <p style={textStyle}>{text}</p>
                {status === 3 && <span className='gray-text'>审核结果将发送到您的消息通知里</span>}
            </div>

            <div className='pd-12' style={{marginTop: '80px',}}>
                {statusDatas[status].button}
            </div>

        </div>
    }


    render() {

        const state = this.state
        const stepsData = state.stepsData
        const status = state.status
        const quizList = state.quizList

        const titleTemplate = <>
            <div className='pd-t-4px pd-l-12px' style={{position: 'relative',}}>
                <p className='pro-apply-title'>专家申请</p>
                <img className='pro-apply-title-block' src={proTitleBlock} alt=""/>
            </div>
            <p className='pd-l-12px pd-t-4px gray-text mg-b-24px'>完善以下信息并认证成功，即可发布方案！</p>
        </>

        const stepTemplate = <div className="flex-space-between-align-center pd-24-px">
            {stepsData.map((stepData, index) => {
                const title = stepData.title
                const finished = stepData.finished
                const cur = stepData.cur
                let cls = 'step-index'
                if (cur) {
                    cls = 'step-index step-index-cur'
                }
                if (finished) {
                    cls = 'step-index step-index-finished'
                }
                const last = index === stepsData.length - 1
                return <React.Fragment key={index}>
                    <div className='step-item'>
                        <div
                            className={cls}
                        >
                            <span>{index + 1}</span>
                        </div>
                        <span className='step-item-title'>{title}</span>
                    </div>
                    {last
                        ? null
                        : <div className='step-index-between'/>
                    }
                </React.Fragment>
            })}
        </div>

        const init = <div className='text-align-center pd-12'>
            <img
                src={veritySrc}
                alt=""
                className='pro-apply-verify-icon'
            />
            <CustomButton
                onClick={() => this.startRealNameVerify()}
            >
                开始认证
            </CustomButton>
        </div>

        const quizTemplate = <>
            {quizList.map((quiz, index) => {
                const cs = {
                    padding: '16px 20px',
                    marginTop: '8px',
                    background: '#fff',
                }
                let lettes = this.letters
                return <div style={cs} key={quiz.Id}>
                    <p className='mg-b-16px'>{index + 1}. {quiz.Topic}</p>
                    <div>
                        {quiz.Option.map((o, optionIndex) => {
                            return <div
                                key={optionIndex}
                                className='mg-t-12px flex-space-between'
                                onClick={() => this.onOptionClick(index, optionIndex)}
                            >
                                <SelectDot select={o.select}/>
                                <span
                                    className='mg-r-4px'
                                    style={{
                                        lineHeight: '20px',
                                    }}
                                >{`${lettes[optionIndex]}.  `}</span>
                                <span
                                    style={{flex: 1, lineHeight: '20px',}}
                                >{o.text}</span>
                            </div>
                        })}
                    </div>
                </div>
            })}
            <div className='pd-12 mg-t-8px mg-b-12px'>
                <CustomButton
                    onClick={() => this.submitApply()}
                >
                    提交
                </CustomButton>
            </div>

        </>


        let templates = {
            'init': init,
            'realName': <RealInfoForm
                onSuccess={() => this.onRealNameVerifySuccess()}
            />,
            'quiz': quizTemplate,
            'apply': this.renderApplyResultTemplate(this.state.proVerifyStatus),
        }

        let mainTitles = {
            'init': null,
            'realName': '提交信息',
            'quiz': '提交信息',
            'apply': '审核结果',
        }

        return <GoBackLayout
            history={this.props.history}
            containerStyle={{
                background: status === 'init' ? '#fff' : null,
                height: status === 'init' ? '100vh' : null,
            }}
            mainTitle={mainTitles[status]}
        >
            {status !== 'apply'
                ? <div className='pd-12' style={{background: '#fff',}}>
                    {status === 'init' && titleTemplate}
                    {stepTemplate}
                </div>
                : null
            }
            {templates[status]}

        </GoBackLayout>
    }
}

export default withRouter(ProApply)